//
//  SendCoinViewModel.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/6/14.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit
class SendCoinViewModel: BaseViewModel {
    @objc dynamic  var refreshBool = false //监听的状态
//    lazy var dateArr:Array<AssetModel> = {
//        let array:Array<AssetModel> = []
//        return array
//    }()
    var model:AssetModel = AssetModel()
    var address:String = "" // 地址
    var coinMoney:String = "" //数字货币金额
    var kindMoney:String = "" //法币价格
    var smallPrice:String = "0" //最小交易价格
    var poundage:String = "0" //手续费
    var passWord =  "" //交易密码
    var codeNumber = "" //验证码 
    var remarks = "" //备注
    
//    ///币种数组
//    lazy var coninKidArray:Array<TradeCoinModel> = {
//        let array:Array<TradeCoinModel> = []
//        return array
//    }()
    var tradeModel:TradeCoinModel = TradeCoinModel() //交易的选择的币种对应的信息
    
    var selectIndex = 0 //选中的model位置
    var rechargeNumber:Double = 0.00 //不同币种对应手续费基本单位
    
    var type:CoinAccountType? //交易种类
    lazy var sendCoinRequest: SendCoinRequest = {
        let api = SendCoinRequest()
        api.dataReformer = self
        api.paramSource = self
        api.delegate = self
        return api
    }()

    lazy var queryRequest:QueryRequest = {
        let api = QueryRequest()
        api.dataReformer = self
        api.paramSource = self
        api.delegate = self
        return api
    }()
    
    lazy var checkAddress:CheckAddressRequest = {
        let api = CheckAddressRequest()
        api.dataReformer = self
        api.paramSource = self
        api.delegate = self
        return api
    }()
    
    lazy var rechargeArr:Array<ChargeModel> = {
       let array = [ChargeModel]()
        return array
    }()
    
    
    override init(controller: BaseViewController) {
        super.init(controller: controller)
    }
    
//    /// 获取不同币种对应的信息
//    ///
//    /// - Parameter coinName: 币种名称 默认BTC CNY
//    func archiveCoinInformation(block:securityBlock? = nil)  {
//        AppContext.default.getCoinKind { (array) in
//            self.coninKidArray = array
//            self.changeModel()
//            if block != nil {
//                block!()
//            }
//        }
//    }
    

    func changeModel()  {
        if APPAssetInfo.default.coinAssetArr.count > selectIndex {
            model = APPAssetInfo.default.coinAssetArr[selectIndex]
            for smallModel in APPAssetInfo.default.coninKidArray {
                if smallModel.coinCode == self.model.coinCode {
                    self.tradeModel = smallModel
                    self.smallPrice = CYCalculate.cy_intercept(number: smallModel.drawMin != nil ?
                        smallModel.drawMin! : 0, digit: self.tradeModel.coinPrecision ?? 8 )!
                    var name = self.tradeModel.coinName ?? ""
                    let coinName = self.tradeModel.coinCode ?? ""
                    if AppCacheInfo.default.isEnlish {
                         name = " " + (self.tradeModel.coinFullName ?? "")
                    }
                    self.controller?.title = String(format: "%@%@(%@)", kText("发送"),name,coinName)
                    return
                }
            }
        }
    }
    
    
    /// 查询网络费
    ///
    /// - Returns:
    func archiveCharge()  {
        self.request(request: queryRequest, success: {[weak self] (result) in
            if result?["data"] as? [[String:Any]] == nil  {
                return
            }
            for dic in (result?["data"] as! [[String:Any]])  {
                let model = ChargeModel(JSON: dic)
                if model != nil {
                    self?.rechargeArr.append(model!)
                }
            }
            self?.archiCharge()
            self?.refreshBool = true
        }) { (response) in
            
        }
    }
    
    ///获取手续费
    func archiCharge() {
        for model in rechargeArr {
            if model.coinCode == self.model.coinCode {
                self.rechargeNumber = model.data
                self.chargeNumber()
            }
        }
    }
    
    
    func sendCoin()  {
        
        self.request(request: self.sendCoinRequest, success: {[weak self] (result) in
            NotificationCenter.default.post(name: NSNotification.Name.Exchange.assetDidChange, object: nil)
            CYMBShow.showMessage(kText("提币申请成功"))
            for popView in ((self?.controller?.navigationController as! WrapNavigationController).wrapViewController?.navigationController?.viewControllers)! {
                let viewController = (popView as? WrapViewController)?.contentViewController
                if (viewController?.isKind(of: AssetViewController.self))! {
                    self?.controller?.navigationController?.popToViewController(viewController!, animated: true)
                    return
                }
            }
            self?.controller?.navigationController?.popViewController(animated: true)
            
        }) { (reponse) in
            CYMBShow.showMessage(reponse.errorMsg.count != 0 ? reponse.errorMsg : "")
        }
    }
    
    
    /// 校验发送币条件
    ///
    /// - Parameter returnValue: 回调
    func checkStates(returnValue:@escaping (_ canSend:Bool) -> ()) {
        if address.count == 0 {
            CYMBShow.showMessage(kText("请填写收币地址"))
            return
        }
        if coinMoney.count == 0 {
            CYMBShow.showMessage(kText("请输入发送价格"))
            return
        }
        if (coinMoney as NSString).doubleValue > model.currentAmount {
            CYMBShow.showMessage(kText("当前账户余额不足"))
            return
        }
        if (coinMoney as NSString).doubleValue < (smallPrice as NSString).doubleValue {
            CYMBShow.showMessage(kText("提币金额不能小于最小提币金额"))
            return
        }
        if !AppSecurityInfo.default.model.isTradePwd {
            CYMBShow.showMessage(kText("请先设置交易密码"))
            return
        }
        if !AppSecurityInfo.default.model.isOpenGoogle && !AppSecurityInfo.default.model.isMobileBind{
            CYMBShow.showMessage(kText("请先绑定手机或开启谷歌验证"))
            return
        }
        
        self.checkCoinAddress(returnVale: returnValue)
    }
    
    
    /// 校验地址是否正确
    ///
    /// - Parameter returnVale: 回调
    func checkCoinAddress(returnVale:@escaping (_ canSend:Bool) -> ()) {
        self.request(request: checkAddress, success: { (result) in
            returnVale(true)
        }) { (response) in
            CYMBShow.showMessage(response.errorMsg)
            returnVale(false)
        }
        
    }
    
    
    /// 获取法币价格
    ///
    /// - Parameter coin: 数字货币金额
    /// - Returns: 法币价格
    func archiveLeveMoeny(coin:String) {
        if coin == "" {
            kindMoney = ""
            return
        }
        let money =  AppContext.default.archiveLegalPrice(coinKind: AppCacheInfo.default.currency, legalKind: model.coinCode.count != 0 ? (model.coinCode) : "")
        let levelMoeny = CYCalculate.cy_multiplying(firstNumber: coin, lastNumber: money, digit: 2)
        kindMoney = levelMoeny
    }
    
    
    /// 根据价格获取对应的手续费
    func chargeNumber() {
        
        poundage = CYCalculate.cy_intercept(number: rechargeNumber, digit: self.tradeModel.coinPrecision ?? 8 )!
    }
    
    ///获取最小提币金额
    func archiveSmallPrice(block:@escaping ()->()) {
        for smallModel in APPAssetInfo.default.coninKidArray {
            if smallModel.coinCode == self.model.coinCode {
                self.smallPrice = CYCalculate.cy_intercept(number: smallModel.drawMin != nil ?
                    smallModel.drawMin! : 0, digit: self.tradeModel.coinPrecision ?? 8 )!
                self.tradeModel = smallModel
                block()
                return
            }
        }
    }
    
    
    /// 清除信息
    func clear() {
        coinMoney = ""
        address = ""
        kindMoney = ""
        poundage = "0"
        rechargeNumber = 0.00
    }
}

extension SendCoinViewModel: RequestCallBack,RequestDataReformer,RequestParamSource {
    func reform(_ request: BaseRequest, _ data: [String : Any]?) {
        if successBlock != nil {
            successBlock!(data)
        }
    }
    
    func requestDidSucess(_ request: BaseRequest) {
        
    }
    
    func requestDidFail(_ request: BaseRequest) {
        if failBlock != nil {
            failBlock!(request)
        }
    }
    
    func requestParams(_ request: BaseRequest) -> [String : Any]? {
        var pramas: [String:Any] = [:]
        if let _ = request as? SendCoinRequest {
            pramas.updateValue(model.coinCode, forKey: "coinCode")
            pramas.updateValue(address, forKey: "drawAdd")
            pramas.updateValue(coinMoney, forKey: "drawAmount")
            pramas.updateValue(poundage, forKey: "poundageAmount")
            pramas.updateValue(passWord, forKey: "tradePwd")
            pramas.updateValue(11, forKey: "checkType")
            pramas.updateValue(remarks, forKey: "mark")
            pramas.updateValue(codeNumber, forKey: "validatePwd")
            if AppSecurityInfo.default.model.isOpenGoogle {
              pramas.updateValue(1, forKey: "validateType")
            }else if AppSecurityInfo.default.model.isMobileBind {
                pramas.updateValue(0, forKey: "validateType")
                pramas.updateValue(AppSecurityInfo.default.model.mobile, forKey: "mobile")
            }
            
        }else if let _ = request as? QueryRequest {
            var coinStr = ""
            for model in APPAssetInfo.default.coinAssetArr {
                if coinStr.count == 0 {
                    coinStr = coinStr + String(format: "%@", model.coinCode)
                }else {
                    coinStr = coinStr + String(format: ",%@", model.coinCode)
                }
            }
            pramas.updateValue(coinStr, forKey: "coinCode")
        }else if let _ = request as? CheckAddressRequest {
            pramas.updateValue(address, forKey: "drawAdd")
            pramas.updateValue(model.coinCode, forKey: "coinCode")
        }
        
        return pramas
    }
    
    
    
}
